'use strict'

//改变工作目录，切换到__dirname所在目录
process.chdir(__dirname)

const titbit = require('titbit')
const fs = require('fs')
const { send } = require('process')

const pg = require('pg')
const dbconfig = require('./dbconfig.js')
const wxkey = require('./wxkey.js')
const tbloader = require('titbit-loader')
const token = require('titbit-token')

let tok = new token({
    //token有效期，单位是秒
    expires: 3600,

    //必须是32位字母数字
    key: '1fuwine75ernej8vrw4ft8d3gdwf95sb',

    //必须是16位字母数字
    iv: '4fg6rtgd5vbnd7hz'
})

//使用HTTP/1.1的客户端
const { httpcli } = require('gohttp')


//初始化数据库连接,创建连接池
let psql = new pg.Pool(dbconfig)

try {
    fs.accessSync('./images')
} catch (err) {
    fs.mkdirSync('./images')
}

let cert_path = '/usr/local/share';

const app = new titbit({
    //开启调试模式，会输出错误信息
    debug: true,
    globalLog: true,
    cert: `${cert_path}/wx.116dajun.xyz.pem`,
    key: `${cert_path}/wx.116dajun.xyz.key`
})

//tb的实例化一定要在app实例之后
let tb = new tbloader();
tb.init(app);

//就是在app.service对象上添加了一个属性
app.addService('tok',tok);
app.addService('psql',psql);

app.addService('imagePath',`${__dirname}/images`)


//添加一个get请求,c就是context
app.get('/', async c => {
    c.send('ok')
})

app.get('/upload', async c => {
    //c.helper是助手函数模块，其中有对stream.pipe的封装
    //c.reply是响应对象，http/1.1中指向response，http/2中指向stream
    await c.helper.pipe('./upload.html', c.reply)
})


app.get('/mp-login/:code', async c => {

    let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
        + `?appid=${wxkey.appid}`
        + `&secret=${wxkey.secret}`
        + `&js_code=${c.param.code}`
        + `&grant_type=authorization_code`

    let ret = await httpcli.get(auth_url)
        .then(res => {
            return res.json()
        })
    c.send(tok.make(ret))
})

//监听·1801运行服务
app.run(1801)